package cn.lyh.FoodSystem.Service.ImpI;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.lyh.FoodSystem.Dao.SpeedDao;
import cn.lyh.FoodSystem.Dao.StudyDao;
import cn.lyh.FoodSystem.Dao.VideoDao;
import cn.lyh.FoodSystem.Dto.Result;
import cn.lyh.FoodSystem.Entity.Entry;
import cn.lyh.FoodSystem.Entity.Speed;
import cn.lyh.FoodSystem.Entity.Study;
import cn.lyh.FoodSystem.Entity.Video;
import cn.lyh.FoodSystem.Service.SpeedService;
import cn.lyh.FoodSystem.Service.StudyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static cn.lyh.FoodSystem.Tool.VideoLong.getVideoDuration;

@Service
@Transactional(readOnly = true)
public class SpeedServiceImpI implements SpeedService {

    @Autowired
    private VideoDao videoDao;

    @Autowired
    private SpeedDao speedDao;

    @Autowired
    private StudyService studyService;

    @Autowired
    private StudyDao studyDao;

    @Value("${file.visitPath}")
    private  String visitPath ;

    /**
     * 添加学习时间记录
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED )
    public Result addSpeed(Study study){
        Result result = new Result();
        try {
            List<Video> videoList = videoDao.findByType(study.getCourseId());
            result.setMsg("添加成功");
            result.setCode(200);
            Double total =0.0;
            for (Video item:videoList){
                String  totalLong = getVideoDuration(visitPath+"\\"+item.getUrl());
                total = total+Double.valueOf(totalLong);
                Speed speed = new Speed();
                speed.setStudyId(String.valueOf(study.getId()));
                speed.setVideoId(String.valueOf(item.getId()));
                speed.setVideoUrl(item.getUrl());//视频路由
                speed.setVideoName(item.getName());//视频名称
                speed.setCourse(item.getCourse());//课程id
                speed.setSpeed("0");
                speed.setStatus("0");
                speed.setVisitLong("0");
                speed.setTotalLong(totalLong);
                Speed speed1 = speedDao.save(speed);
                if (speed1.getId()==null){
                    result.setMsg("添加失败");
                    result.setCode(400);
                    return  result;
                }
            }
            study.setTotalLong(String.valueOf(total));
            studyDao.save(study);

        }catch (Exception e){
            result.setCode(500);
            result.setMsg("程序错误！");
            result.setData(e.getCause());
        }
        return result;
    }
    /**
     * 查询时长记录
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED )
    public Result querySpeed(String userId){
        Result result = new Result();
        try {
            List<Study> studyList = studyDao.findByUserId(userId);
            studyList.stream()
                    .distinct()
                    .forEach(item -> {
                        String studyId = String.valueOf(item.getId());
                        item.setSpeedList(speedDao.findByStudyId(studyId));
                    });
         result.setCode(200);
         result.setMsg("查询成功");
         result.setData(studyList);
        }catch (Exception e){
            result.setCode(500);
            result.setMsg("程序错误！");
            result.setData(e.getCause());
        }
        return result;
    }
    /**
     * 更新时长记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateSpeed(Speed speed){
        Result result = new Result();
        try {
            Speed speed1= speedDao.getReferenceById(speed.getId());
            BeanUtil.copyProperties(speed,speed1,
                    CopyOptions.create().
                            setIgnoreNullValue(true).
                            setIgnoreError(true));
            speedDao.save(speed1);
         List<Speed> speedList =speedDao.findByStudyId(speed.getStudyId());
         Double visitLong=0.0 ;//观看时长
         Double totalLong=0.0; //总时长
         for (Speed item:speedList){
             totalLong = totalLong+Double.valueOf(item.getTotalLong());
             visitLong = visitLong+Double.valueOf(item.getVisitLong());
         }
         Double speedPren = (visitLong/totalLong)*100;//百分比
         Integer id=Integer.valueOf(speed.getStudyId());
         Study study = new Study();
         study.setId(id);
         study.setVisitLong(String.valueOf(visitLong));
         study.setSpeed(String.valueOf(speedPren));
         Study study1 = studyDao.getReferenceById(id);
            BeanUtil.copyProperties(study,study1,
                    CopyOptions.create().
                            setIgnoreNullValue(true).
                            setIgnoreError(true));
            System.out.println(study1);
            studyDao.save(study1);
          result.setMsg("更新成功");
          result.setCode(200);
        }catch (Exception e){
            result.setCode(500);
            result.setMsg("程序错误！");
            result.setData(e.getCause());
        }
        return result;
    }
    /**
     * 删除时长记录
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED )
    public Result deleteSpeed(Speed speed){
        Result result = new Result();
        try {
         speedDao.deleteById(speed.getId());
            result.setCode(200);
            result.setMsg("删除成功！");
        }catch (Exception e){
            result.setCode(500);
            result.setMsg("程序错误！");
            result.setData(e.getCause());
        }
        return result;
    }
}
